package com.ymdx.util;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.List;

/**
 * excel工具类
 * Created by yangliwei on 2017/8/23.
 */
public class ExcelUtil {
    private static Logger log = LoggerFactory.getLogger(ExcelUtil.class);
    public final static int EVERY_EXPORT_ROWS = 3000;//每一次的导出行数
    public final static int MAX_SHEET_ROWS = 60000;


    /**
     * 创建返回的文件名称
     *
     * @param excelFileName
     * @param response
     */
    public static void createFileName(String excelFileName, HttpServletResponse response) {
        response.reset();// 清除首部的空白行
        try {
            excelFileName = URLEncoder.encode(excelFileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("编码错误", e);
        } finally {
            response.setHeader("Content-disposition", "attachment;filename=" + excelFileName + ".xls");
            response.setContentType("application/msexcel");
        }
    }

    /**
     * 输出标题行
     * @param sheet
     * @param headers
     */
    public static void createHeader(Sheet sheet, String[] headers) {
        Row row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            row.createCell(i).setCellValue(headers[i]);
            sheet.autoSizeColumn(i);
        }
    }

    /**
     * 把page里面的数据输出到excel里面
     *
     * @param wb
     * @param page
     * @param sheet  用数组 用来做传递
     * @param rowNum
     * @param params
     * @param headers
     * @return 下次要输入的位置
     */
    public static Integer write2workbook(Workbook wb, Sheet[] sheet, Page page, Integer rowNum, String[] params, String[] headers) {
        if(wb == null){
            log.error("Workbook不能为空");
            return null;
        }
        List results = page.getResult();
        for (Object obj : results) {
            if (rowNum > MAX_SHEET_ROWS || rowNum == 0) {
                rowNum = 1;
                sheet[0] = wb.createSheet("sheet" + page.getTotalCount() / MAX_SHEET_ROWS);
                //输出标题行
                createHeader(sheet[0],headers);
            }
            rowNum = writeOneRow2workbook(sheet[0], obj, rowNum, params);
        }
        return rowNum;
    }


    /**
     * 写一行数据到workbook里面
     *
     * @param sheet
     * @param obj
     * @param rowNum
     * @param params
     * @return 返回下一次输入的行
     */
    public static Integer writeOneRow2workbook(Sheet sheet, Object obj, Integer rowNum, String[] params) {
        Row row = sheet.createRow(rowNum);
        for (int i = 0; i < params.length; i++) {
            try {
                Method getMethod = obj.getClass().getMethod("get" + firstToUppercase(params[i]));
                Object result = getMethod.invoke(obj);
                row.createCell(i).setCellValue(result.toString());
            } catch (NoSuchMethodException e) {
                log.error(e.getMessage() + "没有该get方法" + params[i]);
            } catch (IllegalAccessException e) {
                log.error(e.getMessage() + "执行get方法失败" + params[i]);
            } catch (InvocationTargetException e) {
                log.error(e.getMessage() + "执行get方法失败" + params[i]);
            }
        }
        return ++rowNum;
    }

    /**
     * 首字符大写
     *
     * @param src
     * @return
     */
    public static String firstToUppercase(String src) {
        StringBuilder sb = new StringBuilder(src);
        sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
        return sb.toString();
    }

}
